﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BSCMFF.Core.DataAccessLayer;
using BSCMFF.Web.UserControls;
using Telerik.Web.UI;

namespace BSCMFF.Web.Pages.Evaluation_Setup
{
    public partial class EvaluationEditMode : System.Web.UI.Page
    {
        private static int categories;// = 1;

        public int Categories 
        { 
            get
            {
                return categories;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (Request.QueryString["EvaluationID"] != null)
                {
                    int evalID = Convert.ToInt32(Request.QueryString["EvaluationID"]);


                    BSCEntities context = new BSCEntities();
                    BSCMFF.Core.DataAccessLayer.Evaluation selectedEval = (from ev in context.Evaluations
                                                                           where ev.ID == evalID
                                                                           select ev).SingleOrDefault();
                    ed.Evalut = selectedEval;
                    ed.DataBind();

                    LoadCategories(evalID);
                    LoadUsers(evalID);
                }
                else
                {
                    RadButtonAddCategory_Click(sender, new EventArgs());
                }
                RadButtonCreate.Visible = true;
                //RadButtonUpdate.Visible = false;
                
            }

            if (IsPostBack)
            {
                PersistDynamicCategories();
            }
            else
            {
                if (Request.QueryString["EvaluationID"] == null)
                {
                    categories = 1;
                }
            }
        }

        //protected void AddCategory(object sender, EventArgs e)
        //{

            

        //    //c.Focus();
        //}

        protected void RadButtonAddCategory_Click(object sender, EventArgs e)
        {
            Control c = LoadControl("~/UserControls/EvaluationQuestionCategory.ascx");

            c.ID = "EQC" + categories++.ToString();
            //((EvaluationQuestionCategory)c).PublicEQ.NumQuestions = Int32.Parse(HiddenFieldCurrentNumQuestions.Value); // EQC0.PublicEQ.NumQuestions;

            PlaceHolderCategories.Controls.Add(c);

        }

        private void LoadUsers(int evalID)
        {
            BSCEntities context = new BSCEntities();

            List<User> users = (from u in context.Users
                                //where u.ID
                                select u).ToList();

            foreach(User user in users)
            {
                EGS.RadListBoxSelectedEmployees.Items.Add(new RadListBoxItem(user.Fullname, user.ID.ToString()));
            }
        }

        private void LoadCategories(int evalID)
        {
            BSCEntities context = new BSCEntities();

            List<Evaluation_Category> cats = (from c in context.Evaluation_Category
                                              where c.Evaluation_FK == evalID
                                             // orderby c.ID descending
                                              select c).ToList();
            categories = 0;
            foreach (Evaluation_Category cat in cats)
            {
                EvaluationQuestionCategory eqc = LoadControl("~/UserControls/EvaluationQuestionCategory.ascx") as EvaluationQuestionCategory;
                eqc.ID = "EQC" + categories; //cat.ID.ToString();
                eqc.CategoryName = cat.Name;

                List<Evaluation_Question> equestions = (from eq in context.Evaluation_Question
                                                        where eq.Evaluation_Category_FK == cat.ID
                                                        
                                                        select eq).ToList();

                eqc.SavedQuestions = equestions;
                eqc.Min = cat.Min;
                eqc.Max = cat.Max;
                /*
                //eqc.SetQuestionsProperties(cat.NumberOfQuestions, cat.Min, cat.Max);
                eqc.CreateQuestion(); //PublicEQ.CreateQuestionLoad(cat.NumberOfQuestions, cat.Min, cat.Max);
                //eqc.PublicEQ.Visible = true;
               // ((Control)eqc.FindControl("RadButtonCreateCategory")).Visible=false;
                Panel pq = eqc.PublicPanelQuestions;
               // pq.Visible = true;
                int i = 0;
                foreach (Evaluation_Question equestion in equestions)
                {
                    RadTextBox rquestion = pq.FindControl("Question" + i.ToString()) as RadTextBox;
                    rquestion.Text = equestion.Question;
                    ++i;
                }
                //EQC0.ID = "Question" + i.ToString();
                */
                PlaceHolderCategories.Controls.AddAt(categories++, eqc);
                
            }
            //RadButtonAddCategory_Click(this, new EventArgs());
        }

        

        private void PersistDynamicCategories()
        {
            for (int i = 0; i < categories; ++i)
            {
                Control c = LoadControl("~/UserControls/EvaluationQuestionCategory.ascx");

                c.ID = "EQC" + i.ToString();
                //((EvaluationQuestionCategory)c).EventAddCategory += AddCategory;

                if (categories == 1)//stupid
                {
                   // ((EvaluationQuestionCategory)c).RadButtonUpdateQuestions_Click(this, new EventArgs());
                }
                PlaceHolderCategories.Controls.Add(c);
               // c.Focus();
            }
        }



        

        protected void UpdateEvaluation(object sender, EventArgs e)
        {
            BSCEntities context = new BSCEntities();

            Evaluation ev = ed.Evalut;

            Evaluation saveEV = (from eval in context.Evaluations
                                 where eval.ID == ev.ID
                                 select eval).SingleOrDefault();

            saveEV.Name = ev.Name;
            saveEV.Description = ev.Description;
            saveEV.StartDate = ev.StartDate;
            saveEV.EndDate = ev.EndDate;
            saveEV.Repetition = ev.Repetition;

            SaveCategoryQuestions();

            try
            {
                context.SaveChanges();
            }
            catch
            {
                throw new Exception();
            }
        }

        private void SaveCategoryQuestions()
        {
            BSCEntities context = new BSCEntities();


            foreach (Control c in PlaceHolderCategories.Controls)
            {
                if(c.GetType() == typeof(EvaluationQuestionCategory))
                {
                    //Evaluation_Category ec = 
                }
            }
        }

        #region CreateEvalution
        protected void CreateEvaluation(object sender, EventArgs e)
        {
            //RadButtonCreate.Visible = false;
            //RadButtonUpdate.Visible = true;
            //radbuttonde

            BSCEntities context = new BSCEntities();
            
            Evaluation ev = ed.Evalut;

            Evaluation eval = (from evaluation in context.Evaluations
                               where evaluation.ID == ev.ID
                               select evaluation).SingleOrDefault();

            if (eval == null)
            {

                context.AddToEvaluations(ev);
            }
            else
            {
                eval.Name = ev.Name;
                eval.Description = ev.Description;
                eval.StartDate = ev.StartDate;
                eval.EndDate = ev.EndDate;
                eval.Repetition = ev.Repetition;

                
            }

            try
            {
                context.SaveChanges();
                if (eval != null)
                {
                    DeleteAllEvaluationObjects(eval.ID);
                }

                CreateCategoryQuestions(ev.ID);
                ConnectEvalautionWithEmployees(ev.ID, EGS.RadListBoxSelectedEmployees.Items);
            }
            catch
            {
                throw new Exception();
            }
            
        }

        private void DeleteAllEvaluationObjects(int eval_ID)
        {
            BSCEntities context = new BSCEntities();

            var questions = (from q in context.Evaluation_Question.Include("Evaluation_Category")
                             where q.Evaluation_Category.Evaluation_FK == eval_ID
                             select q);
            foreach (Evaluation_Question question in questions)
            {
                context.DeleteObject(question);
            }

            var categories = (from c in context.Evaluation_Category
                              where c.Evaluation_FK == eval_ID
                              select c);
            foreach (Evaluation_Category category in categories)
            {
                context.DeleteObject(category);
            }

            var eval_users = (from eu in context.Evaluation_User
                              where eu.Evaluation_FK == eval_ID
                              select eu);
            foreach (Evaluation_User eval_user in eval_users)
            {
                context.DeleteObject(eval_user);
            }

            try
            {
                context.SaveChanges();
            }
            catch
            {
                throw new Exception();
            }
        }

        private void ConnectEvalautionWithEmployees(int eval_ID, RadListBoxItemCollection radListBoxItemCollectionUsers)
        {
            BSCEntities context = new BSCEntities();

            foreach (RadListBoxItem ri in radListBoxItemCollectionUsers)
            {
                Evaluation_User eu = new Evaluation_User();
                eu.Evaluation_FK = eval_ID;
                eu.User_FK = Int32.Parse(ri.Value);

                context.AddToEvaluation_User(eu);
            }
            try
            {
                context.SaveChanges();
            }
            catch
            {
                throw new Exception();
            }
        }

        private void CreateCategoryQuestions(int evalID)
        {
            BSCEntities context = new BSCEntities();

            foreach (Control c in PlaceHolderCategories.Controls)
            {
                if (c.GetType().Name == "usercontrols_evaluationquestioncategory_ascx")
                {
                    EvaluationQuestionCategory eqc = (EvaluationQuestionCategory)c;
                    if (eqc.CategoryName == "")
                    {
                        continue;
                    }
                    Evaluation_Category ec = new Evaluation_Category();
                    ec.Evaluation_FK = evalID;
                    ec.Name = eqc.CategoryName;

                    ec.NumberOfQuestions = eqc.NumberQuestions;
                    ec.Min = eqc.Min;
                    ec.Max = eqc.Max;

                    context.AddToEvaluation_Category(ec);
                    try
                    {
                        context.SaveChanges();
                        CreateQuestions(ec.ID, eqc.PublicPanelQuestions);
                    }
                    catch
                    {
                        throw new Exception();
                    }
                    
                }
            }
        }

        private void CreateQuestions(int categoryID, Panel evaluationQuestions)
        {
            BSCEntities context = new BSCEntities();

            Table t = (Table)evaluationQuestions.FindControl("TableQuestions");
            for (int i = 1; i < t.Rows.Count; ++i)
            {
                Evaluation_Question eq = new Evaluation_Question();
                eq.Question = ((RadTextBox)((t).Rows[i].Cells[0].Controls[0])).Text;
                eq.Evaluation_Category_FK = categoryID;

                context.AddToEvaluation_Question(eq);
            }

            try
            {
                context.SaveChanges();
                
            }
            catch
            {
                throw new Exception();
            }
        }

        #endregion
    }
}